package ua.pp.fland.multithreading.sorting;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Maxim Bondarenko
 * @version 1.0 Jun 29, 2010
 */

public class NumberDataProcessor implements DataProcessor {
    private static final Logger logger = Logger.getLogger(NumberDataProcessor.class);

    public List<Integer> sort(List<Integer> unsortedData) {
        List<Integer> res = new ArrayList<Integer>(unsortedData);
        for (int i = 0; i < res.size() - 1; i += 2) {
            if (res.get(i) > res.get(i + 1)) {
                int temp = res.get(i);
                res.set(i, res.get(i + 1));
                res.set(i + 1, temp);
            }
        }

        return res;
    }

    public List<List<Integer>> groupUnsortedData(List<Integer> unsortedData, int threadsNum) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        int elsPerGroup = unsortedData.size() / threadsNum;
        if (elsPerGroup * threadsNum < unsortedData.size()) {
            elsPerGroup++;
        }
        if (elsPerGroup / 2 < elsPerGroup / 2.0) {
            elsPerGroup++;
        }
        //logger.debug("elsPerGroup = " + elsPerGroup);

        int currGroup = 0;
        int currIndexInGroup = 0;
        res.add(new ArrayList<Integer>());
        for (int i = 0; i < unsortedData.size(); i++) {
            res.get(currGroup).add(unsortedData.get(i));
            currIndexInGroup++;
            if (currIndexInGroup >= elsPerGroup) {
                currGroup++;
                currIndexInGroup = 0;
                res.add(new ArrayList<Integer>());
            }
        }
        return res;
    }
}
